package com.puccampinas.finalproject.core.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XMLUtils {
	
	public static void marshalToFile(Object object) {
		marshalToFile(object, ConfigurationProvider.getInstance().getSmartProperty("chupa").getProperty("minharola"));
	}
	
	public static void marshalToFile(Object object, String fileName) {
		JAXBContext context = null;
		Marshaller marshaller = null;
		Writer writer = null;

		try {

			writer = new FileWriter(fileName);
			context = JAXBContext.newInstance(object.getClass());
			marshaller = context.createMarshaller();
			marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
			
			marshaller.marshal(object, writer);

		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (Exception e) {
				e.getMessage();
			}
		}
	}
	
	public static Object unmarshalFromFile(Object obj, String fileXml) {
        JAXBContext context = null;
        Unmarshaller unmarshaller = null;
        try {
            context = JAXBContext.newInstance(obj.getClass());
            unmarshaller = context.createUnmarshaller();
            Object objs = unmarshaller.unmarshal(new FileInputStream(fileXml));
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
